package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.Group;
import com.rz.admin.entity.GroupResource;
import com.rz.admin.mapper.GroupMapper;
import com.rz.admin.service.IGroupResService;
import com.rz.admin.service.IGroupService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupService extends ServiceImpl<GroupMapper, Group> implements IGroupService {

    @Resource
    private GroupMapper groupMapper;
    @Resource
    private IGroupResService groupResService;

    @Override
    public List<Group> getAdminGroupTree(Integer orgId) {
        Group adminGroup = new Group();
        adminGroup.setOrgId(orgId);
        List<Group> list = queryAdminGroupList(adminGroup);
        return buildGroupTree(list);
    }

    @Override
    public boolean onSave(Group group) {
        if(group.getId()==null){
            group.setCrteTime(LocalDateTime.now());
        }
        saveOrUpdate(group);
        groupMapper.deleteByGroupId(group.getId());
        List<GroupResource> groupResources = new ArrayList<>();
        group.getResInfo().forEach(groupRes -> groupResources.add(new GroupResource(group.getId(),groupRes.getResId(),groupRes.getLeaf())));
        return groupResService.saveBatch(groupResources);
    }

    @Override
    public List<Group> buildGroupTree(List<Group> groupList) {
        List<Group> groups = groupList.stream().filter(res -> res.getParentId().equals(0)).collect(Collectors.toList());
        groups.forEach(res -> {
            buildAdminGroupChildren(res, groupList);
        });
        return groups;
    }

    @Override
    public void buildAdminGroupChildren(Group adminGroup, List<Group> groupList) {
        List<Group> children;
        children = groupList.stream().filter(group -> group.getParentId().equals(adminGroup.getId())).sorted(Comparator.comparing(Group::getId)).collect(Collectors.toList());
        if (children.size() > 0) {
            children.forEach(group -> {
                buildAdminGroupChildren(group, groupList);
            });
        }
        adminGroup.setChildren(children.size() > 0 ? children : null);
    }

    @Override
    public List<Group> queryAdminGroupList(Group adminGroup) {
        QueryWrapper<Group> queryWrapper = new QueryWrapper<>();
        if(adminGroup.getOrgId()!=null){
            queryWrapper.eq("org_id",adminGroup.getOrgId());
        }
        return list(queryWrapper);
    }
}
